/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: GestureLockDialog.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.gesture.lock;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.TextView;

import io.bhex.app.R;
import io.bhex.app.safe.fingerprint.FingerActivity;
import io.bhex.baselib.network.Utils.CookieUtils;
import io.bhex.sdk.account.LoginApi;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.app.gesture.view.GestureView;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.ResultResponse;

/**
 * 手势绘制/校验界面
 */
public class GestureLockDialog extends DialogFragment implements android.view.View.OnClickListener {
	private final static int INPUT_PASSWD_ERROR_COUNT = 5;

	/**
	 * 手机号码
	 */
	public static final String PARAM_PHONE_NUMBER = "PARAM_PHONE_NUMBER";
	/**
	 * 意图
	 */
	public static final String PARAM_INTENT_CODE = "PARAM_INTENT_CODE";

	private TextView mTextTip;
	private FrameLayout mGestureContainer;
	private GestureView mGestureContentView;
	private TextView tvForgetPasswd;

	private int inputPasswdTimes = 0;
	private TextView userNameTx;
	private TopBar topBar;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		setCancelable(false);
		return inflater.inflate(R.layout.gesture_verify_layout, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		this.initViews();
		this.setUpListeners();
		addEvent();
	}

    private void addEvent() {
        this.getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode==KeyEvent.KEYCODE_BACK){
                    dismiss();
                    getActivity().finish();
                    return true;
                }else{
                    return false;
                }
            }
        });
    }

    private void initViews() {
		View view = getView();
		topBar = view.findViewById(R.id.topBar);
		topBar.setLeftOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dismiss();
				getActivity().finish();
			}
		});

		// 手机号码
		userNameTx = view.findViewById(R.id.username);
		userNameTx.setText(this.getProtectedMobile(SPEx.get(AppData.SPKEY.USER_INFO_MOBILE, "")));

		this.mTextTip = view.findViewById(R.id.text_tip);
		this.mGestureContainer = view.findViewById(R.id.gesture_container);
		this.tvForgetPasswd = view.findViewById(R.id.tvForgetPasswd);

		// 初始化一个显示各个点的viewGroup
		this.mGestureContentView = new GestureView(getActivity(), true, SPEx.get(AppData.SPKEY.GESTURE_PWD_KEY,""), new GestureView.GestureCallBack() {
			@Override
			public void onGestureCodeInput(String inputCode) {
			}

			@Override
			public void checkedSuccess() {
//				GestureLockActivity.setGestureLock(false);
				mGestureContentView.clearDrawlineState(0L);

//				AppPageUtil.appGestureIsShow=false;

				LoginApi.autoCheckToken(getActivity(),1,new SimpleResponseListener<ResultResponse>(){
					@Override
					public void onSuccess(ResultResponse response) {
						super.onSuccess(response);
						if (CodeUtils.isSuccess(getActivity(),response,true,true)) {
							if (response.isSuccess()) {
//								ToastUtils.showShort("xuqi success");
								LoginApi.GetUserInfo();
							}else{
//								ToastUtils.showShort("xuqi failed");
							}

						}

//						ToastUtils.showShort(getString(R.string.string_unlock_success));
						AppData.isFirstLaunch = false;
						AppData.isHome=false;
						AppData.HOME_TIME = System.currentTimeMillis();
						dismiss();
						getActivity().finish();


					}

					@Override
					public void onError(Throwable error) {
						super.onError(error);

					}
				});

			}

			@Override
			public void checkedFail() {
				String inputCode = mGestureContentView.getInputCode();

				if (TextUtils.isEmpty(inputCode) || inputCode.length() < 4) {
					mTextTip.setTextColor(getResources().getColor(R.color.red));
					mTextTip.setText(Html.fromHtml("<font color='#ff5361'>"+getString(R.string.string_gesture_min_points_tips)+"</font>"));
					mGestureContentView.clearDrawlineState(300L);
					return;
				}

				inputPasswdTimes++;

				if (inputPasswdTimes < INPUT_PASSWD_ERROR_COUNT) {
					mGestureContentView.clearDrawlineState(300L);
					mTextTip.setTextColor(getResources().getColor(R.color.red));

					if (inputPasswdTimes == 1) {
						mTextTip.setText(getString(R.string.string_draw_gesture_passwd_error, getString(R.string.string_draw_gesture_passwd_error_4)));
					} else if (inputPasswdTimes == 2) {
						mTextTip.setText(getString(R.string.string_draw_gesture_passwd_error, getString(R.string.string_draw_gesture_passwd_error_3)));
					} else if (inputPasswdTimes == 3) {
						mTextTip.setText(getString(R.string.string_draw_gesture_passwd_error, getString(R.string.string_draw_gesture_passwd_error_2)));
					} else if (inputPasswdTimes == 4) {
						mTextTip.setText(getString(R.string.string_draw_gesture_passwd_error, getString(R.string.string_draw_gesture_passwd_error_1)));
					}

					// 左右移动动画
					Animation shakeAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
					mTextTip.startAnimation(shakeAnimation);
				} else {// 手势密码5次输入错误
					showLoginScreen();
				}
			}
		});

		this.mGestureContentView.showGestureTrace(SPEx.get(AppData.SPKEY.GESTURE_TRACE_KEY,true));

		// 设置手势解锁显示到哪个布局里面
		mGestureContentView.setParentView(mGestureContainer);
	}

	@Override
	public void onResume() {
		super.onResume();
		UserInfoBean userInfo = UserInfo.getUserInfo();
		if (userInfo != null) {
			int registerType = userInfo.getRegisterType();
			if (registerType==1) {
				userNameTx.setText(userInfo.getMobile());
			}else{
				userNameTx.setText(userInfo.getEmail());
			}

		}
	}

	private void showLoginScreen() {
//		GestureLockActivity.setGestureLock(false);

		//清除密码
		SPEx.set(AppData.SPKEY.GESTURE_PWD_KEY,"");

		UserInfo.clearUserInfo();
		CookieUtils.clearCookies(getActivity());

//		Intent intent = new Intent(getActivity(), LoginActivity.class);
//		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//		intent.putExtra(AppData.INTENT.LOGIN_CALLER, "");
//		startActivity(intent);
		IntentUtils.goLogin(getActivity(),"");
		dismiss();
		getActivity().finish();
	}

	private void setUpListeners() {
		this.tvForgetPasswd.setOnClickListener(this);
	}

	private String getProtectedMobile(String phoneNumber) {
		if (TextUtils.isEmpty(phoneNumber) || phoneNumber.length() < 11) {
			return "";
		}

		StringBuilder builder = new StringBuilder();
		builder.append(phoneNumber.subSequence(0, 3));
		builder.append("****");
		builder.append(phoneNumber.subSequence(7, 11));

		return builder.toString();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.tvForgetPasswd:// 忘记手势密码锁
				showLoginScreen();
				break;
		}
	}

	@Override
	public void show(FragmentManager manager, String tag) {
		setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar);
		super.show(manager, tag);
	}
}